﻿using System.Reflection;

namespace FireChat.Share.Command;


/// <summary>
/// 指令脚手架
/// </summary>
public static class CommandScaffold
{
    /// <summary>
    /// 获取所有指令
    /// </summary>
    public static IEnumerable<(CommandToken, MethodInfo)> GetCommands<T>()
    {
        List<(CommandToken, MethodInfo)> cmds = new();
        var methods = typeof(T).GetTypeInfo().DeclaredMethods;

        foreach (var i in methods)
        {
            var att = i.GetCustomAttribute<CommandToken>();
            if (att == null) continue;

            cmds.Add((att, i));
        }

        return cmds;
    }

    /// <summary>
    /// 开始获取并执行指令 会阻塞
    /// </summary>
    public static void Start<T>(this CommandMap<T> map) where T : new()
    {
        while (true)
        {
            var input = Console.ReadLine()?.ToLower();
            if (input == null)
            {
                continue;
            }

            Task.Run(() => map.Invoke(input));
        }
    }
}
